package com.ys.controller.api.purchase;

import com.ys.config.MenuId;
import com.ys.entity.purchase.TcgPurchaseAppointOrder;
import com.ys.entity.purchase.TcgPurchaseContract;
import com.ys.entity.purchase.TcgPurchaseContractItem;
import com.ys.entity.sys.TbCompanyBankInfo;
import com.ys.entity.sys.YsCol;
import com.ys.service.purchase.TcgPurchaseContractService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 采购合同单
 */
@Controller
@RequestMapping("/api/inter/tcgPurchaseContract")
public class ApiInterTcgPurchaseContractController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcgPurchaseContractController.class);

    @Autowired
    private CommonApiService<TcgPurchaseContract> commonApiService;

    @Autowired
    private CommonApiService<TcgPurchaseAppointOrder> commonApiServiceByTcgPurchaseAppointOrder;
    @Autowired
    private CommonApiService<TcgPurchaseContractItem> commonApiItemService;

    @Autowired
    private TcgPurchaseContractService tcgPurchaseContractService;

    //菜单id
    private Long menuId = MenuId.TCG_PurchaseContract;

    //权限字符
    private final String PERMISSIONS_VIEW = "tcgPurchaseContract:view";
    private final String PERMISSIONS_ADD = "tcgPurchaseContract:add";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcgPurchaseContract setSeachSql(TcgPurchaseContract cond){

        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间
                //.addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间

                //.addLeftJoin("TCG_PurchaseAppointOrder O ON O.Id = A.PurchaseAppointOrderId ")//预约采购管理表
                .addLeftJoin("TB_CompanyInfo CI ON CI.Vid = A.CompanyInfoVid ")//公司信息
                .addField("CI.Vname AS vname")//购买方公司名称
                .addField("CI.Tax AS tax")//公司税号

                .addLeftJoin("TB_CompanyBankInfo B ON B.Id = A.CompanyBankInfoId ")//公司银行账户管理表
                .addField("B.Vyhzhmc AS vyhzhmc")//付款户名 、 银行账户名称
                .addField("B.Vkhh AS vkhh")//付款银行 、 开户行
                .addField("B.Vyhzh AS vyhzh")//付款银行账户 、 银行账户编码

                .addLeftJoin("TCW_PartnerBankInfo PB ON PB.Id = A.PartnerBankInfoId ")//合作商银行账户管理表
                .addField("PB.PartnerName AS partnerName")//供应方公司名称 、合作方名称
                .addField("PB.Vgssh AS vgssh")//供应方公司税号 、 合作方税号
                .addField("(PB.Vlxr + '&' +  PB.Vgsdh) AS vgsdh")//联系人及方式 、 联系人&联系方式
                .addField("PB.Vyhzhmc AS pbVyhzhmc")//收款户名 、 银行账户名称
                .addField("PB.Vkhh AS pbVkhh")//收款银行 、 开户行
                .addField("PB.Vyhzh AS pbVyhzh")//收款银行账户 、 银行账户编码


                .addLeftJoin("TCG_PurchaseContractItem S ON S.Pbid = A.Bid")//合同单子表
                .addField("S.SubBomNumber AS subBomNumber")//子件BOM数量
                .addField("S.SubPurchaseNum AS subPurchaseNum")//子件采购数量
                .addField("S.SubPurchasePrice AS subPurchasePrice")//子件采购单价
                .addField("S.PurchaseTotalPrice AS purchaseTotalPrice")//子件采购总价

                .addLeftJoin("TCG_PurchaseAppointOrderProductComponent C ON C.Id = S.OrderProductComponentId")//预约采购管理子件表
                .addLeftJoin("TCG_PurchaseAppointOrderItem PC ON C.Pid = PC.Id")//预约采购管理母件表
                .addLeftJoin("TCG_PurchaseAppointOrder PPC ON PPC.Bid = PC.Pbid")//预约采购单母表
                .addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = PPC.Vgsbm")//运营公司管理表

                .addField("PPC.Bid AS appointOrderBid")//预约采购单单号
                .addField("PPC.Vgsbm AS vgsbm")//运营公司编码
                .addField("OCA.Vgsjc AS vgsjc")//运营公司简称
                .addField("PC.ProductCode AS productCode")//商品编码
                .addField("PC.ProductName AS productName")//商品名称
                .addField("PC.CodeMerge AS codeMerge")//合并商品编码
                .addField("PC.ReserveNumber AS reserveNumber")//母件预约数量
                .addField("C.SubCode AS subCode")//子件编码
                .addField("C.SubName AS subName")//子件名称
                .addField("C.SubCodeMerge AS subCodeMerge")//子件合并编码
                //.addField("C.SubBomNumber AS subBomNumber")//子件BOM数量
                //.addField("C.SubBomPrice AS subBomPrice")//子件BOM单价
                .addField("C.SubReserveNumber AS subReserveNumber")//子件预约数量


                .addField("CASE WHEN S.CancelState=0  THEN -1 ELSE A.EffectStock END  _ys_effectStock")//流程状态



                //排序
        .setOrderby("A.Bid DESC");

        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcgPurchaseContract cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgPurchaseContract cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcgPurchaseContract> util = new ExportExcelUtils<>(new TcgPurchaseContract());
            String toFilePath = util.exportExcel(listData, listField, "采购合同单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcgPurchaseContractService.add(params,menuId);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcgPurchaseContractService.update(params,menuId);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tcgPurchaseContractService.del(id);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 流转通过
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            TcgPurchaseContract entity = new TcgPurchaseContract().setId(id).queryFirst();
            return tcgPurchaseContractService.flowPass(entity.getBid(),ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转退回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        try {
            TcgPurchaseContract entity = new TcgPurchaseContract().setId(id).queryFirst();
            return tcgPurchaseContractService.flowRefuse(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            TcgPurchaseContract entity = new TcgPurchaseContract().setId(id).queryFirst();
            return tcgPurchaseContractService.flowInit(entity.getBid(), reason,ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 采购合同单(采购预入库调用)
     */
    @RequestMapping("/purchaseContractPre")
    @ResponseBody
    public LayuiTableVoJA purchaseContractPre(com.bo.annotation.Model model, HttpServletRequest request, HttpServletResponse response,
                                           @ModelAttribute TcgPurchaseContract cond
    ) {
        try {
            cond.addField("A.bid purchaseContractBid")
                    .addLeftJoin("TCW_PartnerBankInfo C on C.id = A.PartnerBankInfoId")//供应方公司
                    .addField("C.PartnerName partnerBankInfoName")
                    //.addLeftJoin("TCG_PurchaseAppointOrder pao on pao.id = A.PurchaseAppointOrderId")//预约采购单
                    .addLeftJoin("TB_CompanyInfo D ON D.Vid = A.CompanyInfoVid")//购买方公司
                    .addField("D.Vname companyName")
                    .where("(SELECT SUM(pci.SubPurchaseNum - pci.SubPreWarehousingNum) FROM TCG_PurchaseContractItem pci WHERE pci.Pbid = A.bid AND pci.CancelState = 1) > 0 ")
                    .setStatus(1)
                    .setEffectStock(1)
                    .setOrderby("A.createTime DESC")
                    .queryMap();

            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        } catch (Exception e) {
            logger.error("查询出错：", e.getMessage(), e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }

    }

    /**
     * 预约采购单(采购合同单调用)
     */
    @RequestMapping("/modalByPurchaseAppointOrder")
    @ResponseBody
    public LayuiTableVoJA modalByPurchaseAppointOrder(com.bo.annotation.Model model, HttpServletRequest request, HttpServletResponse response,
                                                      @ModelAttribute TcgPurchaseAppointOrder cond, String conditions) {
        cond
                .addLeftJoin("TB_CompanyInfo CI ON CI.Vid = A.CompanyVid ")//公司信息
                .addField("CI.Vname AS vname")//购买方公司名称
                .addField("CI.Tax AS tax")//公司税号

                //.addLeftJoin("TCG_PurchaseAppointOrderItem PC ON A.Bid = PC.Pbid")//预约采购管理母件表
                //.addLeftJoin("TCG_PurchaseAppointOrderProductComponent C ON C.Pid = PC.Id")//预约采购管理子件表
                //.where("C.StateAppointPurchase !=1")
                .setStateCancel(0)//是否取消，0否1是

                .setStatus(1)
                .setEffectStock(1);

        cond.where("( SELECT COUNT ( 1 ) AS num FROM TCG_PurchaseAppointOrderItem PC " +
                "LEFT JOIN TCG_PurchaseAppointOrderProductComponent C ON C.Pid = PC.Id WHERE A.Bid = PC.Pbid AND C.StateAppointPurchase !=1 ) > 0 ");

        LayuiTableVoJA tableVoJA = commonApiServiceByTcgPurchaseAppointOrder.searchLay(cond);
        return tableVoJA;

    }



    /**
     * 预约采购单子表信息(采购合同单调用)
     */
    @RequestMapping("/modalByOrderProductComponent")
    @ResponseBody
    public LayuiTableVoJA modalByOrderProductComponent(com.bo.annotation.Model model, HttpServletRequest request, HttpServletResponse response,
                                                      @ModelAttribute TcgPurchaseAppointOrder cond, String conditions) {
        cond

                .addLeftJoin("TCG_PurchaseAppointOrderItem PC ON A.Bid = PC.Pbid")//预约采购管理母件表
                .addLeftJoin("TCG_PurchaseAppointOrderProductComponent C ON C.Pid = PC.Id")//预约采购管理子件表
                .addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = A.Vgsbm")//运营公司管理表


                //.addLeftJoin("TCG_PurchaseAppointOrder PPC ON PPC.Bid = C.Pid")
                .addLeftJoin("TB_CompanyInfo CI ON CI.Vid = A.CompanyVid ")//公司信息
                .addField("CI.Vname AS vname")//购买方公司名称

                .addField("C.Id AS orderProductComponentId")//预约采购管理子件表id
                .addField("A.Bid AS appointOrderBid")//预约采购单单号
                .addField("A.Vgsbm AS vgsbm")//运营公司编码
                .addField("OCA.Vgsjc AS vgsjc")//运营公司简称
                .addField("PC.ProductCode AS productCode")//商品编码
                .addField("PC.ProductName AS productName")//商品名称
                .addField("PC.CodeMerge AS codeMerge")//合并商品编码
                .addField("PC.ReserveNumber AS reserveNumber")//母件预约数量
                .addField("C.SubCode AS subCode")//子件编码
                .addField("C.SubName AS subName")//子件名称
                .addField("C.SubCodeMerge AS subCodeMerge")//子件合并编码
                .addField("C.SubBomNumber AS subBomNumber")//子件BOM数量
                .addField("C.SubBomPrice AS subBomPrice")//子件BOM单价
                .addField("C.SubReserveNumber AS subReserveNumber")//子件预约数量

                .where("C.StateAppointPurchase = 0 ")//预约采购完整性为否
                .setStateCancel(0)//是否取消，0否1是
                .setStatus(1)
                .setEffectStock(1);

        //调取未被调取的
        cond.where("( SELECT COUNT ( 1 ) AS num FROM TCG_PurchaseContractItem B WHERE B.OrderProductComponentId = C.Id AND B.CancelState !=0 ) = 0 ");

        LayuiTableVoJA tableVoJA = commonApiServiceByTcgPurchaseAppointOrder.searchLay(cond);
        return tableVoJA;

    }


    /*
     * 采购合同管理(采购预入库调用)
     */
    @RequestMapping("/purchaseContractItemSonPre")
    @ResponseBody
    public LayuiTableVoJA purchaseContractItemSonPre(com.bo.annotation.Model model, HttpServletRequest request, HttpServletResponse response,
                                              @ModelAttribute TcgPurchaseContractItem cond,String conditions,String purchaseContractBid
    ) {
        try {

            cond.addField("A.Pbid purchaseContractBid,A.SubPurchasePrice subPurchasePrice,A.id purchaseContractItemId")
                    .addLeftJoin("TCG_PurchaseAppointOrderProductComponent paoc on paoc.id = A.OrderProductComponentId")//预约采购子件明细
                    .addField("paoc.SubCode subCode,paoc.subName subName,paoc.subCodeMerge subCodeMerge")
                    .addLeftJoin("TCG_PurchaseAppointOrderItem paoi on paoi.id = paoc.pid")//预约采购商品明细
                    .addField("paoi.Pbid appointOrderBid,paoi.ProductCode productCode,paoi.ProductName productName,paoi.CodeMerge codeMerge")
                    .addLeftJoin("TCG_PurchaseAppointOrder pao on pao.Bid = paoi.Pbid")//预约采购单
                    .addLeftJoin("THR_OperateCompanyApply TOCA ON TOCA.Vgsbm = pao.Vgsbm")
                    .addField("pao.Vgsbm vgsbm,TOCA.Vgsjc AS vgsjc")//运营公司简称
                    .addField("A.SubPurchaseNum -  A.SubPreWarehousingNum AS subNotStorageNum")//未预入库数量
                    .where(" A.CancelState = 1 AND A.pbid = '"+ purchaseContractBid + "'" + " AND (A.SubPurchaseNum -  A.SubPreWarehousingNum) >0")
                    .queryMap();

            LayuiTableVoJA tableVoJA = commonApiItemService.searchLay(cond);
            return tableVoJA;
        } catch (Exception e) {
            logger.error("查询出错：", e.getMessage(), e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }

    }

    /*
     * 采购付款单调用
     */
    @RequestMapping("/tcgPurchaseContractcg")
    @ResponseBody
    public LayuiTableVoJA tcgPurchaseContractcg(@ModelAttribute TcgPurchaseContract cond, String conditions){
        cond = setSeachSql(cond)
                .addField("A.bid purchaseContractBid")
                .addField("A.createTime _ys_CreateTime")
                .addField("S.id purchaseContractItemId")
                .addField("S.subPaymentNum")
                .where("S.SubPaymentNum < S.SubPurchaseNum")//子件付款数量＜子件采购数量
                .setEffectStock(1)
                .setOrderby("A.createTime DESC");
        return commonApiService.searchLay(cond);
    }

}